package com.xjcs.saplingplan.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Path
import android.util.AttributeSet
import android.view.View
import com.xjcs.saplingplan.R
import kotlin.random.Random

class WaterDropView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    // 水滴属性 - 每次只允许一滴
    private var currentDrop: WaterDrop? = null
    private var currentRipple: RippleEffect? = null
    private val paint = Paint(Paint.ANTI_ALIAS_FLAG)

    // 状态控制
    private var isDroppingEnabled = true
    private var dropInterval = 1000L // 默认滴落间隔(毫秒)

    // 颜色配置
    private var waterColor = Color.argb(220, 64, 164, 223)
    private var highlightColor = Color.argb(180, 255, 255, 255)
    private var rippleColor = Color.argb(120, 135, 206, 250)

    // 配置参数
    private var dropSize = 20f
    private var dropSpeed = 800L // 下落时间(毫秒)
    private var rippleDuration = 200L // 涟漪持续时间

    // 中心位置
    private val centerX get() = width / 2f
    private val bottomY get() = height - dropSize * 3

    // 动画状态
    private var isDropComplete = true

    init {
        setupPaint()
        setupAttributes(attrs)
    }

    private fun setupPaint() {
        paint.style = Paint.Style.FILL
    }

    private fun setupAttributes(attrs: AttributeSet?) {
        attrs?.let {
            val typedArray = context.obtainStyledAttributes(it, R.styleable.WaterDropView)
            waterColor = typedArray.getColor(R.styleable.WaterDropView_waterColor, waterColor)
            rippleColor = typedArray.getColor(R.styleable.WaterDropView_rippleColor, rippleColor)
            dropSize = typedArray.getDimension(R.styleable.WaterDropView_dropSize, dropSize)
            dropSpeed = typedArray.getInt(R.styleable.WaterDropView_dropSpeed, dropSpeed.toInt()).toLong()
            dropInterval = typedArray.getInt(R.styleable.WaterDropView_dropInterval, dropInterval.toInt()).toLong()
            typedArray.recycle()
        }
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        // 绘制当前水滴
        currentDrop?.let { drop ->
            drawWaterDrop(canvas, drop)
        }

        // 绘制当前涟漪效果
        currentRipple?.let { ripple ->
            drawRipple(canvas, ripple)
        }

        // 更新动画状态
        updateAnimations()
    }

    private fun drawWaterDrop(canvas: Canvas, drop: WaterDrop) {
        // 绘制水滴主体
        paint.color = waterColor
        canvas.drawPath(createDropPath(drop), paint)

        // 绘制高光效果
        paint.color = highlightColor
        canvas.drawCircle(
            drop.x - drop.size * 0.25f,
            drop.y - drop.size * 0.3f,
            drop.size * 0.15f,
            paint
        )
    }

    private fun drawRipple(canvas: Canvas, ripple: RippleEffect) {
        paint.color = rippleColor
        paint.alpha = (255 * (1 - ripple.progress)).toInt()
        canvas.drawCircle(ripple.x, ripple.y, ripple.maxRadius * ripple.progress, paint)
    }

    private fun createDropPath(drop: WaterDrop): Path {
        val path = Path()
        val height = drop.size * 2.2f
        val width = drop.size * 1.5f

        // 水滴形状路径
        path.moveTo(drop.x, drop.y - height / 2)

        // 右侧曲线
        path.cubicTo(
            drop.x + width / 3, drop.y - height / 3,
            drop.x + width / 2, drop.y,
            drop.x + width / 4, drop.y + height / 2
        )

        // 底部尖角
        path.quadTo(
            drop.x, drop.y + height / 1.8f,
            drop.x - width / 4, drop.y + height / 2
        )

        // 左侧曲线
        path.cubicTo(
            drop.x - width / 2, drop.y,
            drop.x - width / 3, drop.y - height / 3,
            drop.x, drop.y - height / 2
        )

        path.close()
        return path
    }

    private fun updateAnimations() {
        // 更新水滴位置
        currentDrop?.let { drop ->
            drop.progress += (16f / dropSpeed) // 基于60fps的进度更新

            if (drop.progress >= 1f) {
                // 水滴落到底部，创建涟漪
                createRippleEffect(drop.x, bottomY)
                currentDrop = null
                isDropComplete = true

                // 如果自动滴落启用，立即开始下一滴
                if (isDroppingEnabled) {
                    startNextDrop()
                }
            } else {
                // 更新水滴位置
                drop.y = -dropSize + (height + dropSize * 2) * drop.progress
            }
        }

        // 更新涟漪效果
        currentRipple?.let { ripple ->
            ripple.progress += (16f / rippleDuration) // 基于60fps的进度更新

            if (ripple.progress >= 1f) {
                currentRipple = null
            }
        }

        // 如果需要继续动画，请求重绘
        if (currentDrop != null || currentRipple != null) {
            invalidate()
        }
    }

    private fun createRippleEffect(x: Float, y: Float) {
        currentRipple = RippleEffect(
            x = x,
            y = y,
            maxRadius = dropSize * 4f,
            progress = 0f
        )
        invalidate() // 触发重绘
    }

    // 开始下一滴水滴（间隔控制）
    private fun startNextDrop() {
        if (!isDropComplete || !isDroppingEnabled) {
            return
        }

        isDropComplete = false

        // 添加延迟，模拟间隔效果
        postDelayed({
            if (isDroppingEnabled) {
                addSingleDrop()
            }
        }, dropInterval)
    }

    // 开始自动滴落（上一滴完成后立即开始下一滴）
    fun startAutoDrops() {
        if (!isDroppingEnabled) {
            isDroppingEnabled = true
        }

        // 如果当前没有水滴，立即开始第一滴
        if (currentDrop == null && isDropComplete) {
            startNextDrop()
        }
    }

    // 添加单滴水滴（从正中间顶部）
    fun addSingleDrop() {
        if (width == 0 || height == 0) {
            post { addSingleDrop() }
            return
        }

        // 确保只有一滴水
        if (currentDrop == null) {
            currentDrop = WaterDrop(
                x = centerX, // 正中间
                y = -dropSize, // 从顶部开始
                size = dropSize + Random.nextFloat() * 3f, // 轻微随机大小
                progress = 0f
            )

            invalidate() // 触发重绘
        }
    }

    // 暂停新水滴的生成（当前水滴继续完成）
    fun pauseNewDrops() {
        isDroppingEnabled = false
    }

    // 继续生成新水滴（如果当前没有水滴，立即开始）
    fun resumeNewDrops() {
        isDroppingEnabled = true

        // 如果当前没有水滴且上一滴已完成，立即开始新的一滴
        if (currentDrop == null && isDropComplete) {
            startNextDrop()
        }
    }

    // 停止所有水滴（包括正在下落的）
    fun stopAllDrops() {
        isDroppingEnabled = false
        currentDrop = null
        currentRipple = null
        isDropComplete = true
        invalidate()
    }

    // 设置滴落间隔
    fun setDropInterval(interval: Long) {
        dropInterval = interval
    }

    // 设置水滴大小
    fun setDropSize(size: Float) {
        dropSize = size
        invalidate()
    }

    // 设置下落速度
    fun setDropSpeed(speed: Long) {
        dropSpeed = speed
    }

    // 获取当前状态
    fun getDropState(): String {
        return when {
            currentDrop != null -> "滴落中"
            currentRipple != null -> "涟漪中"
            isDropComplete -> "已完成"
            else -> "空闲"
        }
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        stopAllDrops()
    }

    // 水滴数据类
    private data class WaterDrop(
        var x: Float,
        var y: Float,
        var size: Float,
        var progress: Float
    )

    // 涟漪效果数据类
    private data class RippleEffect(
        var x: Float,
        var y: Float,
        var maxRadius: Float,
        var progress: Float
    )
}